package net.cyue.homework.student.management.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import net.cyue.homework.student.management.util.ResponseUtil;
import net.cyue.nest.nestjava.common.enums.HTTPStatus;
import net.cyue.nest.nestjava.common.interfaces.http.IHTTPResponse;
import net.cyue.nest.nestjava.platform.tomcat.TomcatHTTPResponse;

import java.io.IOException;

@WebFilter(
    urlPatterns = {
        "/action/user",
        "/action/user/",
        "/api/*",
        "/user.jsp",
        "/admin.jsp",
        "/admin_major.jsp",
        "/admin_class.jsp",
        "/admin_job.jsp"
    }
)
public class UserLoginFilter implements Filter {

    @Override
    public void doFilter(
        ServletRequest request,
        ServletResponse response,
        FilterChain chain
    ) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        IHTTPResponse ihttpResponse = new TomcatHTTPResponse(httpServletResponse);
        String method = httpServletRequest.getMethod();

        // 不拦截注册请求
        if (
            httpServletRequest.getRequestURI().contains("/action/user") &&
            method.equalsIgnoreCase("post")
        ) {
            chain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }

        HttpSession session = httpServletRequest.getSession();
        Integer userID = (Integer) session.getAttribute("userID");
        if (userID == null) {
            ihttpResponse.code(HTTPStatus.UNAUTHORIZED);
            ResponseUtil.backHomeMessage(ihttpResponse, "请先登录");
            return;
        }

        chain.doFilter(httpServletRequest, httpServletResponse);
    }
}

